package com.example.word.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.word.MyApplication;
import com.example.dict.R;
import com.example.word.adapter.DictAdapter;
import com.example.word.bean.Dict;
import com.example.word.bean.StudyPlan;
import com.example.word.bean.Word;
import com.example.word.ui.fragment.HomeFragment;
import com.example.word.util.AlwaysMarqueeTextView;
import com.example.word.util.KeyBoardUtil;
import com.example.word.util.MessageUtils;
import com.example.word.util.SPUtils;
import com.example.word.widget.ActionBar;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 搜索
 */
public class SearchActivity extends AppCompatActivity {
    private ActionBar mTitleBar;//标题栏
    private Activity myActivity;
    private RecyclerView recyclerView;
    private DictAdapter dictAdapter;
    private LinearLayout llEmpty;
    private Boolean mIsAdmin;
    private EditText etQuery;//搜索内容
    private ImageView ivSearch;//搜索图标
    private List<Dict> dictList;
    private String account;
    private AlwaysMarqueeTextView systemMsg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        myActivity = this;
        recyclerView = findViewById(R.id.rv_dict_list);
        llEmpty = findViewById(R.id.ll_empty);
        etQuery = findViewById(R.id.et_query);
        ivSearch = findViewById(R.id.iv_search);
        systemMsg = findViewById(R.id.systemMsg);
        mTitleBar = (ActionBar) findViewById(R.id.myActionBar);
        mTitleBar.setData(myActivity, "搜索", R.drawable.ic_back, 0, 0, getResources().getColor(R.color.colorPrimary), new ActionBar.ActionBarClickListener() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {
            }
        });
        // 设置主题
        if (!com.example.word.ui.activity.MainActivity.colorChange) {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        } else {
            mTitleBar.setBackgroundColor(getResources().getColor(R.color.myColor));
        }
        //获取控件
        initView();
        //搜索
        ivSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ProgressDialog dialog = new ProgressDialog(myActivity);
                dialog.setMessage("正在搜索···");
                dialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadData();//加载数据
                        dialog.dismiss();
                    }
                }, 505);
            }
        });
        //点击软键盘中的搜索
        etQuery.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                ProgressDialog dialog = new ProgressDialog(myActivity);
                dialog.setMessage("正在搜索···");
                dialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                            KeyBoardUtil.hideKeyboard(v);//隐藏软键盘
                            loadData();//加载数据
                            // return true;
                        }
                        dialog.dismiss();
                    }
                }, 505);
                return false;
            }
        });

    }

    /**
     * 初始化页面
     */
    private void initView() {
        mIsAdmin = (Boolean) SPUtils.get(myActivity, SPUtils.IS_ADMIN, false);
        account = (String) SPUtils.get(myActivity, SPUtils.ACCOUNT, "");
        LinearLayoutManager layoutManager = new LinearLayoutManager(myActivity);
        //=1.2、设置为垂直排列，用setOrientation方法设置(默认为垂直布局)
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //=1.3、设置recyclerView的布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //==2、实例化适配器
        //=2.1、初始化适配器
        dictAdapter = new DictAdapter(llEmpty, recyclerView);
        //=2.3、设置recyclerView的适配器
        recyclerView.setAdapter(dictAdapter);
        loadData();
        dictAdapter.setItemListener(new DictAdapter.ItemListener() {
            @Override
            public void ItemClick(Dict dict) {
                boolean isAdmin = (boolean) SPUtils.get(myActivity, SPUtils.IS_ADMIN, false);
                String account = (String) SPUtils.get(myActivity, SPUtils.ACCOUNT, "");
                if ("".equals(account)) {//未登录,跳转到登录页面
                    MyApplication.Instance.getMainActivity().finish();
                    startActivity(new Intent(myActivity, LoginActivity.class));
                } else {//已经登录
                    Intent intent = null;
                    if (isAdmin) {
                        intent = new Intent(myActivity, AddActivity.class);
                        intent.putExtra("dict", dict);
                        startActivityForResult(intent, 100);
                    } else {
                        // 判断是否已经下载过
                        ProgressDialog dialog = new ProgressDialog(myActivity);
                        dialog.setMessage("正在加载单词···");
                        dialog.show();

                        // 去有道词典下载词汇
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (!"downloaded".equals(dict.getWordFileUrl())) {
                                    // 开始远程下载
                                    // saveWord(dict.getWordFileUrl(), dict.getTitle());
                                    OkHttpClient client = new OkHttpClient();
                                    Request request = new Request.Builder().url(dict.getWordFileUrl()).build();

                                    client.newCall(request).enqueue(new Callback() {
                                        @Override
                                        public void onResponse(Call call, Response response) {
                                            if (response.isSuccessful()) {
                                                // 创建目标文件夹
                                                // 获取应用的私有目录
                                                File folder = myActivity.getExternalFilesDir(null);
                                                // 保存下载的ZIP文件
                                                File zipFile = new File(folder, dict.getTitle() + ".zip");
                                                try (OutputStream outputStream = new FileOutputStream(zipFile)) {
                                                    outputStream.write(response.body().bytes());
                                                } catch (Exception e) {
                                                    com.example.word.util.ExceptionUtils.printExceptionDetail(e);
                                                }

                                                // 解压缩ZIP文件
                                                try {
                                                    int wordCount = 0;
                                                    List<Word> saveWords = new ArrayList<>(dict.getWordNumber());
                                                    try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile))) {
                                                        ZipEntry zipEntry;

                                                        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                                                            if (!zipEntry.isDirectory() && zipEntry.getName().endsWith(".json")) {
                                                                // Read JSON content line by line
                                                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                                                byte[] buffer = new byte[1024];
                                                                int bytesRead;

                                                                while ((bytesRead = zipInputStream.read(buffer)) != -1) {
                                                                    baos.write(buffer, 0, bytesRead);
                                                                }

                                                                byte[] data = baos.toByteArray();
                                                                try (BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(data)))) {
                                                                    String line;
                                                                    while ((line = reader.readLine()) != null) {
                                                                        wordCount++;
                                                                        // Process each line of JSON content
                                                                        JSONObject jsonWord = new JSONObject(line);
                                                                        Log.d("单词行" + wordCount, line);
                                                                        //HomeFragment.buildSaveWord(jsonWord, dict.getTitle());
                                                                        saveWords.add(HomeFragment.buildSaveWord(jsonWord, dict.getTitle()));
                                                                        try {
                                                                            dialog.setMessage(String.format("正在下载单词(%s/%s)···", wordCount, dict.getWordNumber()));
                                                                        } catch (Exception e) {
                                                                        }
                                                                    }

                                                                    Word.saveAll(saveWords);
                                                                }
                                                            }
                                                        }
                                                    }

                                                    // 下载完成之后清除文件地址
                                                    dict.setWordFileUrl("downloaded");
                                                    dict.setWordNumber(saveWords.size());
                                                    dict.save();
                                                    Intent intent = new Intent(myActivity, UnitActivity.class);
                                                    intent.putExtra("wordCount", wordCount);
                                                    intent.putExtra("dict", dict.getTitle());
                                                    dialog.dismiss();
                                                    startActivityForResult(intent, 100);
                                                } catch (Exception e) {
                                                    com.example.word.util.ExceptionUtils.printExceptionDetail(e);
                                                    MessageUtils.show("解析单词信息出现错误 " + e.getMessage(), myActivity);

                                                }
                                            }
                                        }

                                        @Override
                                        public void onFailure(Call call, IOException e) {
                                            com.example.word.util.ExceptionUtils.printExceptionDetail(e);
                                        }
                                    });
                                } else {
                                    // 直接查询数据库有多少单词
                                    int wordCount = Word.where("dict = ?", dict.getTitle()).count(Word.class);
                                    Intent intent = new Intent(myActivity, UnitActivity.class);
                                    intent.putExtra("wordCount", wordCount);
                                    intent.putExtra("dict", dict.getTitle());
                                    dialog.dismiss();
                                    startActivityForResult(intent, 100);
                                }
                            }
                        }, 1005);

                    }
                }
            }
        });
    }

    private void loadData() {
        if ("".equals(account)) {
            systemMsg.setText(LoginActivity.systemMessage);
        } else {
            StudyPlan studyPlan = StudyPlan.queryCurrentUserPlan(account);
            systemMsg.setText(String.format("系统消息: 您今日学习目标为%s个单词，今日已学习%s个单词，累计学习了%s个单词，继续加油噢！", studyPlan.getDayTask(), studyPlan.getTodayCount(), studyPlan.getTotalCount()));
        }
        String content = etQuery.getText().toString();//获取搜索内容
        if ("".equals(content)) {
            dictList = DataSupport.where().find(Dict.class);
        } else {
            dictList = DataSupport.where("title like ?", "%" + content + "%").find(Dict.class);//通过标题模糊查询
        }
        if (dictList != null && dictList.size() > 0) {
            recyclerView.setVisibility(View.VISIBLE);
            llEmpty.setVisibility(View.GONE);
            dictAdapter.addItem(dictList);
        } else {
            recyclerView.setVisibility(View.GONE);
            llEmpty.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            loadData();//加载数据
        }
    }
}
